# -*- coding: utf-8 -*-

import sys
import re
import qrc_resources
import tabela as TABELA  
import os
import nltk
import re
from PyQt4.QtCore import *
from PyQt4.QtGui import *

try:
    _fromUtf8 = QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s:s

class MainWindow(QMainWindow):

    NextId = 1 # número de arquivos abertos
    Instances = set() # ...
    TEXTO = ""
    TF = ""

    def __init__(self, filename = QString(), parent=None):
        
        super(MainWindow, self).__init__(parent)       
        self.setAttribute(Qt.WA_DeleteOnClose)
        MainWindow.Instances.add(self)      
        self.nometexto = QLabel(self)
        self.nometexto.setGeometry(QRect(55,57,50,50))
        self.nometexto.setObjectName(_fromUtf8("nometexto"))
        self.nometexto.setText(QApplication.translate("MainWindow", "Review", None, QApplication.UnicodeUTF8))  #criancao das tabs
        self.tabWidget = QTabWidget(self) 
        self.tabWidget.setGeometry(QRect(40,40, 1100, 850))
        self.tabWidget.setObjectName(_fromUtf8("tabWidget"))

#----------------------------------------------------------------------------------------------------------------        
        self.tabManualTagging = QWidget() #First Tab
        self.tabManualTagging.setObjectName(_fromUtf8("tabManualTagging"))
            
        self.editor = QTextEdit(self.tabManualTagging)                    
        self.editor.setGeometry(30,50,470,700)
        
        self.model = TABELA.ShipTableModel(QString("TABELA.dat"))

        self.TABLE = QTableView(self.tabManualTagging)     
        self.TABLE.setGeometry(QRect(570,175, 335, 550))
        self.TABLE.setModel(self.model)
        self.TABLE.setItemDelegate(TABELA.ShipDelegate(self))

        self.addLineButton = QPushButton(self.tabManualTagging)
        self.addLineButton.setGeometry(QRect(580,100, 100, 37))
        self.addLineButton.setText(QApplication.translate("None","Add", None, QApplication.UnicodeUTF8))
        
        self.removeLineButton = QPushButton(self.tabManualTagging)
        self.removeLineButton.setGeometry(QRect(680, 100, 100, 37))
        self.removeLineButton.setText(QApplication.translate("None","Remove", None, QApplication.UnicodeUTF8))

        self.exportButton = QPushButton(self.tabManualTagging)
        self.exportButton.setGeometry(QRect(780, 100, 100, 37))        
        self.exportButton.setText(QApplication.translate("None","Export", None, QApplication.UnicodeUTF8))
        
        self.connect(self.addLineButton, SIGNAL("clicked()"), self.addLine)
        self.connect(self.removeLineButton, SIGNAL("clicked()"), self.removeLine)
        self.connect(self.exportButton, SIGNAL("clicked()"), self.export)
        
        self.setWindowTitle("Program (delegate)")

        self.tabWidget.addTab(self.tabManualTagging, _fromUtf8("")) 
#----------------------------------------------------------------------------------------------------------------        
        self.tabPreProcessing = QWidget() #Second tab                           
        self.tabPreProcessing.setObjectName(_fromUtf8("tabPreProcessing")) 
        
        self.TextProcessTab2 = QTextEdit(self.tabPreProcessing)                    
        self.TextProcessTab2.setGeometry(30,50,470,700)

        self.ProcessButtonTab2 = QPushButton(self.tabPreProcessing)
        self.ProcessButtonTab2.setGeometry(QRect(580,100, 130, 47))
        self.ProcessButtonTab2.setText(QApplication.translate("None","Run", None, QApplication.UnicodeUTF8))
        self.connect(self.ProcessButtonTab2, SIGNAL("clicked()"), self.pre_processamento)

        self.tabWidget.addTab(self.tabPreProcessing, _fromUtf8(""))   
#-----------------------------------------------------------------------------------------------------------------        
        self.tabOntology = QWidget() #Third tab
        self.tabOntology.setObjectName(_fromUtf8("tabOntology"))
        
        self.TextProcessTab3 = QTextEdit(self.tabOntology)                    
        self.TextProcessTab3.setGeometry(30,50,470,700)

        self.ProcessButtonTab3 = QPushButton(self.tabOntology)
        self.ProcessButtonTab3.setGeometry(QRect(580,100, 130, 47))
        self.ProcessButtonTab3.setText(QApplication.translate("None","Run", None, QApplication.UnicodeUTF8))
        self.connect(self.ProcessButtonTab3, SIGNAL("clicked()"), self.ontologia)        
        
        self.tabWidget.addTab(self.tabOntology, _fromUtf8(""))
#---------------------------------------------------------------------------------------------------------------        
        self.tabSentimentLexicon = QWidget() #Fourth tab
        self.tabSentimentLexicon.setObjectName(_fromUtf8("tabSentimentLexicon"))
        
        self.TextProcessTab4 = QTextEdit(self.tabSentimentLexicon)                    
        self.TextProcessTab4.setGeometry(30,50,470,700)

        self.ProcessButtonTab4 = QPushButton(self.tabSentimentLexicon)
        self.ProcessButtonTab4.setGeometry(QRect(580,100, 130, 47))
        self.ProcessButtonTab4.setText(QApplication.translate("None","Run", None, QApplication.UnicodeUTF8))
        self.connect(self.ProcessButtonTab4, SIGNAL("clicked()"), self.lexico_de_sentimento)
        
        self.tabWidget.addTab(self.tabSentimentLexicon, _fromUtf8(""))
#-----------------------------------------------------------------------------------------------------------------        
        self.tabResults = QWidget() #Fifth tab
        self.tabResults.setObjectName(_fromUtf8("tabResults"))
        
        self.TextProcessTab5 = QTextEdit(self.tabResults)                    
        self.TextProcessTab5.setGeometry(30,50,470,700)

        self.ProcessButtonTab5 = QPushButton(self.tabResults)
        self.ProcessButtonTab5.setGeometry(QRect(580,100, 130, 47))
        self.ProcessButtonTab5.setText(QApplication.translate("None","Run", None, QApplication.UnicodeUTF8))
        self.connect(self.ProcessButtonTab5, SIGNAL("clicked()"), self.resultados)
        
        self.tabWidget.addTab(self.tabResults, _fromUtf8(""))
#-----------------------------------------------------------------------------------------------------------------           

        fileNewAction = self.createAction("&New", self.fileNew, QKeySequence.New, "filenew", "Create a text file") #cria um novo file
        fileOpenAction = self.createAction("&Open", self.fileOpen, QKeySequence.Open, "fileopen", "Open self.parent().export()    an existing text file") #abre um file existente                           
        fileSaveAction = self.createAction("&Save", self.fileSave, QKeySequence.Save, "filesave", "Save the text") #salva um file (apenas texto)                          
        fileCloseAction = self.createAction("&Close", self.close, QKeySequence.Close, "fileclose", "Close this text editor") #fecha um file                    
        fileQuitAction = self.createAction("&Quit", self.fileQuit, "Ctrl+m", "filequit", "Close the application") #fecha todas as janelas                    
        editCopyAction = self.createAction("&Copy", self.editor.copy, QKeySequence.Copy, "editcopy", "Copy text to the clipboard") #copia alguma parte do texto, sublinha e clica no "copy" na parte superior da janela do programa para copiar            
        editCutAction = self.createAction("&Cut", self.editor.cut, QKeySequence.Cut, "editcut", "Cut text to the clipboard") #corta alguma parte do texto, sublinha e clica no "cut" na parte superior da janela do programa para cortar                      
        editPasteAction = self.createAction("&Paste", self.editor.paste, QKeySequence.Paste, "editpaste", "Paste in the clipboard's text") #clica na linha que deseja, depois clica em paste para postar o que voce havia copiado por ultimo
        editInsertAction = self.createAction("&Insert", self.addLineTable, QKeySequence.Print,"Insert", "Insert in the clipboard's text")

        fileMenu = self.menuBar().addMenu("&File")         
        self.addActions(fileMenu, (fileNewAction, fileOpenAction, fileSaveAction, None, fileCloseAction, fileQuitAction))
                
        editMenu = self.menuBar().addMenu("&Edit")        
        self.addActions(editMenu, (editCopyAction, editCutAction, editPasteAction, editInsertAction))

        self.windowMenu = self.menuBar().addMenu("&Window")
        
        self.connect(self.windowMenu, SIGNAL("aboutToShow()"), self.updateWindowMenu)

        fileToolbar = self.addToolBar("File")
        fileToolbar.setObjectName("FileToolbar")
        self.addActions(fileToolbar, (fileNewAction, fileOpenAction,fileSaveAction))

        editToolbar = self.addToolBar("Edit")
        editToolbar.setObjectName("EditToolbar")
        self.addActions(editToolbar, (editCopyAction, editCutAction, editPasteAction))

        self.connect(self, SIGNAL("destroyed(QObject*)"), MainWindow.updateInstances)

        self.resize(1500, 1200)
        self.scroll(400,400)

        self.setWindowTitle(QApplication.translate("Form", filename, None, QApplication.UnicodeUTF8))

        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabManualTagging), QApplication.translate("Form", "Manual Tagging", None, QApplication.UnicodeUTF8))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabPreProcessing), QApplication.translate("Form", "Preprocessing", None, QApplication.UnicodeUTF8))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabOntology), QApplication.translate("Form", "Ontology", None, QApplication.UnicodeUTF8))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabSentimentLexicon), QApplication.translate("Form", "Sentiment Lexicon", None, QApplication.UnicodeUTF8))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabResults), QApplication.translate("Form", "Results", None, QApplication.UnicodeUTF8))
        
        self.filename = filename
        
        if self.filename.isEmpty():
            self.filename = QString("Unnamed-%d.txt" % MainWindow.NextId)
            MainWindow.NextId += 1
            self.editor.document().setModified(False)
            self.setWindowTitle("MAIN WINDOW  - %s" % self.filename)
        else:
            self.loadFile()

    @staticmethod
    def updateInstances(qobj):

        MainWindow.Instances = set([window for window in MainWindow.Instances if isAlive(window)])     

    def fileOpen(self):

        filename = QFileDialog.getOpenFileName(self,"MAIN WINDOW -- Open File")
        if not filename.isEmpty():
            if not self.editor.document().isModified() and self.filename.startsWith("Unnamed"):
                self.filename = filename
                self.loadFile() #utiliza o load onde está a abertura do owl
            else:
                MainWindow(filename).show()        
       
    def loadFile(self):
        
        global text
        fh = None
        arquivo = open('filme.owl',"r").read() #abertura do arquivo 
        o = re.compile('<rdfs:comment xml:lang="pt">.*</rdfs:comment>')
        dadosPt = o.findall(arquivo)
        listaDeClasses = []
        saida = open("./ln1.txt","w")
        for classeSuja in dadosPt:
            classeLimpa = re.sub("<[^>]*>", "", classeSuja)
            listaDeClasses = listaDeClasses + [classeLimpa.lower()]            
        for i in listaDeClasses:
            saida.write(i+"\n")
        saida.close()
       
        try:
            fh = QFile(self.filename)
            if not fh.open(QIODevice.ReadOnly):
                raise IOError, unicode(fh.errorString())
            stream = QTextStream(fh)
            stream.setCodec("UTF-8")
            text = stream.readAll()
            self.TEXTO = text
            self.TF = self.filename
            self.editor.setPlainText(text)
            self.editor.document().setModified(False)
        except (IOError, OSError), e:
            QMessageBox.warning(self, "MAIN WINDOW -- Load Error", "Failed to load %s: %s" % (self.filename, e))
        finally:
            if fh is not None:
                fh.close()
        self.editor.document().setModified(False)
        self.setWindowTitle("MAIN WINDOW - %s" %  QFileInfo(self.filename).fileName())    
        
        return text        
    
    # metodo para adicionar linha, incrementa o numero dela , utilizei depois esse mesmo row como um contador.
    def addLine(self):
                        
        row = self.model.rowCount()   
        self.model.insertRows(row)
        index = self.model.index(row, 0)
        tableView = self.TABLE        
        tableView.setFocus()
        tableView.setCurrentIndex(index)
        tableView.edit(index)

    # metodo para remover uma linha da tabela, clica em algum dos objetos dessa linha e clica para deletar, ele deleta toda a linha.
    def removeLine(self):
             
        tableView = self.TABLE
        index = tableView.currentIndex()
        if not index.isValid():            
            return "index isValid"
        row = index.row()
        TSentence = self.model.data(self.model.index(row, TABELA.SENTENCE)).toString()                    
        TPolarity = self.model.data(self.model.index(row, TABELA.POLARITY)).toString()
        TFeature = self.model.data(self.model.index(row, TABELA.FEATURE)).toString()
        if QMessageBox.question(self, "Line - Remove", 
                QString("Remove %1 of %2/%3?").arg(TSentence).arg(TPolarity).arg(TFeature),
                QMessageBox.Yes|QMessageBox.No) == QMessageBox.No:
            return
        self.model.removeRows(row)

    def pre_processamento(self):
        
        conteudo = ""
        marcacao = ""
 
        listaDeComentarios = str(self.TEXTO).decode("utf-8")
        listaDeComentarios = re.sub("\n","", listaDeComentarios) 
        listaDeComentarios = re.sub("\'","", listaDeComentarios)
        listaDeComentarios = re.sub("\"","", listaDeComentarios)
        sentencas = nltk.sent_tokenize(listaDeComentarios)         

        arquivo = []
        palavras = []
        tamanho = 0
        n=-1

        for sentenca in sentencas:   
            
            palavras = nltk.word_tokenize(sentenca) # quebra por palavra             
            tamanho = len(palavras)
            arquivo = nltk.pos_tag(palavras) # marcacao POS por palavra  
      
            n=n+1
            self.TextProcess.setPlainText(conteudo + " " + marcacao)
            for n in range(0,tamanho):
                conteudo = conteudo + arquivo[n][0] +" "+ arquivo[n][1] +" "
                
        self.TextProcess.setPlainText(conteudo)
      
    def ontologia(self):
        print "carregar ontologia"
        
    def lexico_de_sentimento(self):
        print "carregar léxico de sentimento"
                
    def resultados(self):
        print "apresentar resultados"
          
    # adiciona linha, incrementa o numero dela , utilizei depois esse mesmo row como um contador.
    def addLineTable(self):
        
        row = self.model.rowCount()   #create a line into my tableview
        self.model.insertRows(row)
        column = 0
        index = self.model.index(row, column)        
        tableView = self.TABLE            
        tableView.setFocus()
        tableView.setCurrentIndex(index)
        cursor = self.editor.textCursor()

        # get the current format
        format = cursor.charFormat()
        # modify it
        format.setBackground(Qt.red)
        format.setForeground(Qt.blue)
        # apply it
        cursor.setCharFormat(format)
        # set text to cursor
        textSelected = cursor.selectedText()  
        # set text to new tableview 
        self.model.setData(index, QVariant(textSelected))    
    
    def export(self):
        
        nomeArquivo = "nomeArquivo"
        filename = unicode(QFileDialog.getSaveFileName(self, "Document - Choose Export File", nomeArquivo+".xml"))
        if not filename:
                return "filename"
        self.model.sortByCountryOwner()
        fh = None
        try:
            
                fh = QFile(filename)
                if not fh.open(QIODevice.WriteOnly):                     
                    raise IOError, unicode(fh.errorString())
                stream = QTextStream(fh)
                stream.setCodec("UTF-8")              
                for row in range(self.model.rowCount()):
                    TSentence = self.model.data(
                    self.model.index(row, TABELA.SENTENCE)).toString()
                    TPolarity = self.model.data(   
                    self.model.index(row, TABELA.POLARITY)).toString()
                    TFeature = self.model.data(
                    self.model.index(row, TABELA.FEATURE)).toString()
                    stream << "<document id="+str(row)+">" << "\n" << text << "\n" << "\t" << "<sentence id="+str(row)+"> " << "\n" << "\t" << "\t" << TSentence << "\n" << "\t" << "\t" << "\t" << "<feature id="+str(row)+">" << "\t" << TFeature << "\t" << "</feature>" << "\n" << "\t" << "\t" << "\t" << "<polarity id="+str(row)+">" << "\t" << TPolarity << "\t" << "</polarity>" << "\n" << "\n" << "\t" << "</sentence>" << "\n" << "</document>"<< "\n" << "\n"
                    
        except (IOError, OSError), e:
            QMessageBox.warning(self, "Text - Error",
                    "Failed to export: %s" % e)
            
        finally:
            if fh:
                fh.close()
        QMessageBox.warning(self, "Text - Export",
                "Successfully exported text to %s" % filename)

    def createAction(self, text, slot=None, shortcut=None, icon=None,   #criacao icones
                     tip=None, checkable=False, signal="triggered()"):
        
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % icon))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action

    # adiciona as criacoes aos respectivos "objetos"
    def addActions(self, target, actions):
         
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)
    
    def fileQuit(self):
        
        QApplication.closeAllWindows()

    def fileNew(self):
        
        MainWindow().show()

    def fileSave(self):
        
        if self.filename.startsWith("Text"):
            return self.fileSaveAs()
        fh = None
        try:
            fh = QFile(self.filename)
            if not fh.open(QIODevice.WriteOnly):
                raise IOError, unicode(fh.errorString())
            stream = QTextStream(fh) #utiliza o QTextStream tanto p/ o save, p/ o load...
            stream.setCodec("UTF-8")
            stream << self.editor.toPlainText()
            self.editor.document().setModified(False) 
        except (IOError, OSError), e:         
            QMessageBox.warning(self, "Program -- Save Error", "Failed to save %s: %s" % (self.filename, e))
        finally:
            if fh is not None:
                fh.close()
        return True 

    def updateWindowMenu(self):
        
        self.windowMenu.clear()
        for window in MainWindow.Instances:
            if isAlive(window):
                self.windowMenu.addAction(window.windowTitle(),self.raiseWindow)

    def raiseWindow(self):
        
        action = self.sender()
        if not isinstance(action, QAction):
            return
        for window in MainWindow.Instances:
            if isAlive(window) and window.windowTitle() == action.text():  
                window.activateWindow()
                window.raise_()
                break
           
def isAlive(qobj):
    
    import sip
    try:
        
        sip.unwrapinstance(qobj)
    except RuntimeError:
        return False
    return True

app = QApplication(sys.argv)
MainWindow().show()
app.setWindowIcon(QIcon(":/icon.png")) 
app.exec_()